// 有序链表
import LinkedList, {equalsType} from "../LinkedList";
import defaultEquals from "../../utils/defaultEquals";
import Node from "../Node";
import {Compare,compareType,defaultCompare} from "../../utils/Compare"

export default class SortedLinkedList<T> extends LinkedList<T> {
    compare: compareType<T>;

    constructor(equalsFn: equalsType<T> = defaultEquals, compareFn: compareType<T> = defaultCompare) {
        super(equalsFn);
        this.compare = compareFn
    }


    getIndexNextSortedElement(el: T) {
        let current = this.head;
        let i = 0;
        if(!this.head){
            return i;
        }
        for (let size = this.size(); i < size; i++) {
            if(this.compare(el,(current as Node<T>).value as T) === Compare.LESS_THAN){
                return i;
            }
            current = current?.next;
        }
        return i;
    }

    insert(element: T, index: number = 0) {
        const insertIndex = this.getIndexNextSortedElement(element)
        super.insert(element, insertIndex);
    }

}
